package com.yin.myproject.thread.spinlock;

import java.util.ArrayList;

/**
 * @author Eason
 * @create 2018-03-07 10:19
 **/
public class TimeCost implements Lock {

    private static ArrayList<Long> list = new ArrayList<>();
    private final Lock lock;

    public TimeCost(Lock lock) {
        this.lock = lock;
    }

    public static long getAvg() {
        int size = list.size();
        long sum = 0;
        for (int i = 0; i < size; i++) {
            sum += list.get(i);
        }
        return sum / size;
    }

    @Override
    public void lock() {
        long start = System.nanoTime();
        lock.lock();
        long duration = System.nanoTime() - start;
        list.add(duration);
    }

    @Override
    public void unlock() {
        lock.unlock();
    }

    @Override
    public String toString() {
        return lock.toString();
    }
}
